import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { prisma, dbOperation } from '@/lib/db';
import { ProjectRole } from '@prisma/client';

// 获取项目成员列表
export async function GET(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const projectId = searchParams.get('projectId');

    if (!projectId) {
      return NextResponse.json(
        { success: false, message: '未提供项目ID' },
        { status: 400 }
      );
    }

    // 验证用户是否为项目成员
    const userMembership = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
        },
      });
    });

    if (!userMembership.success || !userMembership.data) {
      return NextResponse.json(
        { success: false, message: '您不是该项目的成员' },
        { status: 403 }
      );
    }

    // 获取项目成员
    const members = await dbOperation(async () => {
      return prisma.projectUser.findMany({
        where: {
          projectId,
        },
        include: {
          user: {
            select: {
              id: true,
              name: true,
              email: true,
              image: true,
            },
          },
        },
      });
    });

    if (!members.success) {
      return NextResponse.json(
        { success: false, message: '获取项目成员失败', error: members.error },
        { status: 500 }
      );
    }

    // 格式化返回数据
    const formattedMembers = members.data.map((member) => ({
      id: member.id,
      userId: member.userId,
      projectId: member.projectId,
      role: member.role,
      joinedAt: member.joinedAt,
      user: {
        id: member.user.id,
        name: member.user.name,
        email: member.user.email,
        image: member.user.image
      }
    }));

    return NextResponse.json({ success: true, data: formattedMembers });
  } catch (error: any) {
    console.error('获取项目成员失败:', error);
    return NextResponse.json(
      { success: false, message: '获取项目成员失败', error: error.message },
      { status: 500 }
    );
  }
}

// 添加项目成员
export async function POST(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const { projectId, email, role = 'MEMBER' } = body;

    if (!projectId || !email) {
      return NextResponse.json(
        { success: false, message: '缺少必填参数' },
        { status: 400 }
      );
    }

    // 验证角色是否有效
    const validRoles = ['ADMIN', 'MEMBER', 'VIEWER'];
    if (!validRoles.includes(role)) {
      return NextResponse.json(
        { success: false, message: '无效的角色类型' },
        { status: 400 }
      );
    }

    // 验证用户是否有权限添加成员
    const userRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
          role: {
            in: ['OWNER', 'ADMIN'],
          },
        },
      });
    });

    if (!userRole.success || !userRole.data) {
      return NextResponse.json(
        { success: false, message: '您没有权限添加项目成员' },
        { status: 403 }
      );
    }

    // 查找要添加的用户
    const targetUser = await dbOperation(async () => {
      return prisma.user.findUnique({
        where: {
          email,
        },
      });
    });

    if (!targetUser.success) {
      return NextResponse.json(
        { success: false, message: '查找用户失败', error: targetUser.error },
        { status: 500 }
      );
    }

    if (!targetUser.data) {
      return NextResponse.json(
        { success: false, message: '未找到该邮箱对应的用户' },
        { status: 404 }
      );
    }

    // 检查用户是否已经是项目成员
    const existingMember = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: targetUser.data.id,
        },
      });
    });

    if (!existingMember.success) {
      return NextResponse.json(
        { success: false, message: '检查用户关系失败', error: existingMember.error },
        { status: 500 }
      );
    }

    if (existingMember.data) {
      return NextResponse.json(
        { success: false, message: '该用户已经是项目成员' },
        { status: 400 }
      );
    }

    // 添加成员到项目
    const newMember = await dbOperation(async () => {
      return prisma.projectUser.create({
        data: {
          projectId,
          userId: targetUser.data.id,
          role: role as ProjectRole,
        },
        include: {
          user: {
            select: {
              id: true,
              name: true,
              email: true,
              image: true,
            },
          },
        },
      });
    });

    if (!newMember.success) {
      return NextResponse.json(
        { success: false, message: '添加项目成员失败', error: newMember.error },
        { status: 500 }
      );
    }

    // 创建通知
    await dbOperation(async () => {
      return prisma.notification.create({
        data: {
          type: 'PROJECT_INVITATION',
          title: '项目邀请',
          content: `您已被添加到项目中，角色为${role === 'ADMIN' ? '管理员' : role === 'MEMBER' ? '成员' : '观察者'}`,
          recipients: {
            create: {
              userId: targetUser.data.id,
            },
          },
        },
      });
    });

    // 格式化返回数据
    const formattedMember = {
      id: newMember.data.id,
      userId: newMember.data.userId,
      name: newMember.data.user.name,
      email: newMember.data.user.email,
      image: newMember.data.user.image,
      role: newMember.data.role,
      joinedAt: newMember.data.joinedAt,
    };

    return NextResponse.json(
      { success: true, message: '成员添加成功', data: formattedMember },
      { status: 201 }
    );
  } catch (error: any) {
    console.error('添加项目成员失败:', error);
    return NextResponse.json(
      { success: false, message: '添加项目成员失败', error: error.message },
      { status: 500 }
    );
  }
}

// 更新项目成员角色
export async function PATCH(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const { projectId, userId, role } = body;

    if (!projectId || !userId || !role) {
      return NextResponse.json(
        { success: false, message: '缺少必填参数' },
        { status: 400 }
      );
    }

    // 验证角色是否有效
    const validRoles = ['ADMIN', 'MEMBER', 'VIEWER'];
    if (!validRoles.includes(role)) {
      return NextResponse.json(
        { success: false, message: '无效的角色类型' },
        { status: 400 }
      );
    }

    // 验证用户是否有权限更新成员角色
    const userRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
          role: {
            in: ['OWNER', 'ADMIN'],
          },
        },
      });
    });

    if (!userRole.success || !userRole.data) {
      return NextResponse.json(
        { success: false, message: '您没有权限更新项目成员角色' },
        { status: 403 }
      );
    }

    // 检查目标成员是否是项目所有者，所有者角色不能被修改
    const targetMember = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId,
        },
      });
    });

    if (!targetMember.success) {
      return NextResponse.json(
        { success: false, message: '查找成员失败', error: targetMember.error },
        { status: 500 }
      );
    }

    if (!targetMember.data) {
      return NextResponse.json(
        { success: false, message: '未找到该项目成员' },
        { status: 404 }
      );
    }

    if (targetMember.data.role === 'OWNER') {
      return NextResponse.json(
        { success: false, message: '项目所有者的角色不能被修改' },
        { status: 400 }
      );
    }

    // 如果当前用户是管理员，不能修改其他管理员的角色
    if (userRole.data.role === 'ADMIN' && targetMember.data.role === 'ADMIN') {
      return NextResponse.json(
        { success: false, message: '管理员不能修改其他管理员的角色' },
        { status: 403 }
      );
    }

    // 更新成员角色
    const updatedMember = await dbOperation(async () => {
      return prisma.projectUser.update({
        where: {
          id: targetMember.data.id,
        },
        data: {
          role: role as ProjectRole,
        },
        include: {
          user: {
            select: {
              id: true,
              name: true,
              email: true,
              image: true,
            },
          },
        },
      });
    });

    if (!updatedMember.success) {
      return NextResponse.json(
        { success: false, message: '更新成员角色失败', error: updatedMember.error },
        { status: 500 }
      );
    }

    // 格式化返回数据
    const formattedMember = {
      id: updatedMember.data.id,
      userId: updatedMember.data.userId,
      name: updatedMember.data.user.name,
      email: updatedMember.data.user.email,
      image: updatedMember.data.user.image,
      role: updatedMember.data.role,
      joinedAt: updatedMember.data.joinedAt,
    };

    return NextResponse.json({
      success: true,
      message: '成员角色更新成功',
      data: formattedMember,
    });
  } catch (error: any) {
    console.error('更新项目成员角色失败:', error);
    return NextResponse.json(
      { success: false, message: '更新项目成员角色失败', error: error.message },
      { status: 500 }
    );
  }
}

// 从项目中移除成员
export async function DELETE(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const projectId = searchParams.get('projectId');
    const userId = searchParams.get('userId');

    if (!projectId || !userId) {
      return NextResponse.json(
        { success: false, message: '缺少必填参数' },
        { status: 400 }
      );
    }

    // 验证用户是否有权限移除成员
    const userRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
          role: {
            in: ['OWNER', 'ADMIN'],
          },
        },
      });
    });

    if (!userRole.success || !userRole.data) {
      return NextResponse.json(
        { success: false, message: '您没有权限移除项目成员' },
        { status: 403 }
      );
    }

    // 检查目标成员是否是项目所有者
    const targetMember = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId,
        },
      });
    });

    if (!targetMember.success) {
      return NextResponse.json(
        { success: false, message: '查找成员失败', error: targetMember.error },
        { status: 500 }
      );
    }

    if (!targetMember.data) {
      return NextResponse.json(
        { success: false, message: '未找到该项目成员' },
        { status: 404 }
      );
    }

    if (targetMember.data.role === 'OWNER') {
      return NextResponse.json(
        { success: false, message: '项目所有者不能被移除' },
        { status: 400 }
      );
    }

    // 如果当前用户是管理员，不能移除其他管理员
    if (userRole.data.role === 'ADMIN' && targetMember.data.role === 'ADMIN') {
      return NextResponse.json(
        { success: false, message: '管理员不能移除其他管理员' },
        { status: 403 }
      );
    }

    // 移除成员
    const removeMember = await dbOperation(async () => {
      return prisma.projectUser.delete({
        where: {
          id: targetMember.data.id,
        },
      });
    });

    if (!removeMember.success) {
      return NextResponse.json(
        { success: false, message: '移除成员失败', error: removeMember.error },
        { status: 500 }
      );
    }

    return NextResponse.json({ success: true, message: '成员移除成功' });
  } catch (error: any) {
    console.error('移除项目成员失败:', error);
    return NextResponse.json(
      { success: false, message: '移除项目成员失败', error: error.message },
      { status: 500 }
    );
  }
} 